package org.bigjava.novelplatform.common.handlerInterceptor;

import lombok.extern.slf4j.Slf4j;
import org.bigjava.novelplatform.common.enums.UserRole;
import org.bigjava.novelplatform.common.exception.UserActionException;
import org.bigjava.novelplatform.vo.UserInfoVo;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static org.bigjava.novelplatform.common.constant.NovelInfoConstant.SESSION_USER;
import static org.bigjava.novelplatform.common.exception.ExceptionCodeMessage.UN_LOGIN;

/**
 * 身份认证拦截器
 * @author ykh
 * @create 2022-03-20 18:57
 */
@Order(Integer.MAX_VALUE-1)
@Slf4j
public class IdentificationInterceptor implements HandlerInterceptor {
    /**
     * 执行前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //预检请求忽略
        if(HttpMethod.OPTIONS.matches(request.getMethod())){
            return true;
        }
        final HttpSession session = request.getSession(false);
        if (session == null) {
            throw new UserActionException(UN_LOGIN);
        }
        UserInfoVo userInfo = (UserInfoVo)session.getAttribute(SESSION_USER);
        if (userInfo == null) {
            throw new UserActionException(UN_LOGIN);
        }
        log.debug("登录用户：{}",userInfo);
        return true;
    }
}
